package com.heima.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.heima.common.exception.BaseException;
import com.heima.common.result.PageResult;
import com.heima.mapper.NodeMapper;
import com.heima.mapper.RegionMapper;
import com.heima.pojo.dto.PageDTO;
import com.heima.pojo.entity.Region;
import com.heima.pojo.entity.Node;
import com.heima.pojo.vo.RegionPageVO;
import com.heima.service.RegionService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * \* User: chy
 * \* Date: 2025/8/17  13:27
 * \* Description:
 * \
 */
@Service
@Slf4j
public class RegionServiceImpl implements RegionService {

    @Autowired
    private RegionMapper regionMapper;
    @Autowired
    private NodeMapper nodeMapper;

    /**
     * 区域搜索分页查询
     * @param pageDTO
     * @return
     */
    @Override
    @Transactional

    public PageResult<RegionPageVO> page(PageDTO pageDTO) {
        PageHelper.startPage(pageDTO.getPageIndex(), pageDTO.getPageSize());

        //1.查询region的总页数
        Page<Region> regionList = regionMapper.page(pageDTO);

        if (regionList == null && regionList.isEmpty()) {

            throw new BaseException("没有区域内容");
        }

        //2.根据region的id查询所关联的区域点位列表
        List<String> regionIds = regionList.stream()
                .map(Region::getId)
                .filter(Objects::nonNull)
                .collect(Collectors.toList());

        //拿到所有区域点位数据
        List<Node> tbNodeList = new ArrayList<>();

        if(regionIds != null){
            try {
                tbNodeList = nodeMapper.getByRegionIds(regionIds);
            } catch (Exception e) {
                log.info("查询点位数据失败");
            }
        }

        //3.根据regionId分组
        Map<String, List<Node>> listMap = tbNodeList.stream()
                .filter(Objects::nonNull)
                .collect(Collectors.groupingBy(Node::getRegionId));

        //4.封装到输出对象中
        List<RegionPageVO> regionPageVOList = regionList.stream().map(region -> {
            //区域id
            String id = region.getId();

            //创建对象
            RegionPageVO regionPageVO = new RegionPageVO();
            //将属性拷贝到输出对象中
            BeanUtils.copyProperties(region,regionPageVO);

            List<Node> tbNodes = listMap.getOrDefault(id,new ArrayList<>());//拿到对应id下的集合数据
            //设置nodeList
            regionPageVO.setNodeList(tbNodes);
            regionPageVO.setNodeCount(tbNodes.size());
            return regionPageVO;
        }).collect(Collectors.toList());


        long total = regionList.getTotal();//总条数

        return PageResult.<RegionPageVO>builder()
                .pageIndex(pageDTO.getPageIndex())
                .pageSize(pageDTO.getPageSize())
                .totalPage((int) Math.ceil(total / (double) pageDTO.getPageSize()))  //总页数
                .totalCount((int) total)
                .currentPageRecords(regionPageVOList)
        .build();

    }
    /**
     * 新增区域
     * @param region
     * @return
     */
    @Override
    public void add(Region region) {
        regionMapper.add(region);
    }
    /**
     * 修改区域
     * @param region
     * @return
     */
    @Override
    public void updateById(Region region) {

        regionMapper.updateById(region);
    }

    /**
     * 删除区域
     * @param id
     * @return
     */
    @Override
    public void deleteById(String id) {

        regionMapper.deletById(id);
    }
}
